import 'package:dio/dio.dart';
import 'package:enjoy_plus_bryant/utils/http.dart';
import 'package:enjoy_plus_bryant/utils/toast.dart';
import 'package:enjoy_plus_bryant/utils/validate.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class HouseForm extends StatefulWidget {
  HouseForm({super.key, required this.houseData, this.id});
  Map houseData;
  String? id;

  @override
  State<HouseForm> createState() => _HouseFormState();
}

class _HouseFormState extends State<HouseForm> {
  // 表单控制器，获取表单内容
  TextEditingController nameController = TextEditingController();
  TextEditingController mobileController = TextEditingController();
  final Map _formData = {
    'point': '', // 小区信息
    'building': '', // 小区楼栋信息
    'room': '', // 小区房间信息
    'name': '', // 业主姓名
    'gender': 1, // 业主性别0女1男
    'mobile': '', // 业主电话
    'idcardFrontUrl': '', // 身份证正面 assets/images/avatar_1.jpg
    'idcardBackUrl': '', // 身份证背面 assets/images/avatar_1.jpg
  };

  // 未上传身份证
  Widget _buildAddIdcardPhoto(String tag, String info) {
    return GestureDetector(
      onTap: () {
        // 点击之后调用弹层，选择相册或者相机
        onShowSheet(tag);
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(Icons.add, size: 30, color: Color.fromARGB(255, 85, 145, 175)),
          Text(
            '${info}',
            style: TextStyle(color: Color.fromARGB(255, 85, 145, 175)),
          ),
        ],
      ),
    );
  }

  // 身份证图片 - 已上传
  Widget _buildIdcardPhoto(String tag, String photoUrl) {
    return Stack(
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width - 20,
          height: 300,
          child: Image.network(photoUrl, fit: BoxFit.contain),
        ),
        Positioned(
          right: 0,
          top: 0,
          child: GestureDetector(
            child: const Icon(Icons.delete, color: Colors.red),
            onTap: () {
              setState(() {
                // 删除图片
                _formData[tag] = '';
              });
            },
          ),
        ),
      ],
    );
  }

  //提交数据
  submitData() async {
    // 1.  -------------------- 校验表单内容 --------------------
    // 1.1 姓名
    if (!Validate.validateName(nameController.text)) return;
    // 1.2 手机号
    if (!Validate.validatePhone(mobileController.text)) return;
    // 1.3 身份证
    if (!Validate.validateIdCardImg(
      _formData['idcardFrontUrl'],
      _formData['idcardBackUrl'],
    ))
      return;

    // 2. -------------------- 校验通过 - 提交数据 --------------------
    _formData['name'] = nameController.text;
    _formData['mobile'] = mobileController.text;
    if (_formData.containsKey('id')) {
      _formData.remove('status');
    }
    // 发请求
    try {
      var res = await http.post('/room', data: _formData);
      if (res['code'] != 10000) {
        return ToastUtil.showError(res['message']);
      }
      ToastUtil.showSuccess('提交成功');
      // print(res);
      // 回到首页
      Navigator.popUntil(context, (res) {
        return res.settings.name == '/'; // 一直回退，知道回到名称为‘/’
      });
    } catch (e) {
      ToastUtil.showError('提交失败');
    }
  }

  // 弹层 选择照片
  // 展示弹窗
  void onShowSheet(String tag) async {
    // 1. 展示弹窗
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          height: 150,
          padding: const EdgeInsets.all(10),
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                trailing: Icon(Icons.arrow_right),

                title: const Text('拍照'),
                onTap: () {
                  // print('点击拍照');
                  selectType('camera', tag);
                  Navigator.pop(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.image),
                trailing: Icon(Icons.arrow_right),
                title: const Text('相册'),
                onTap: () {
                  // print('点击相册');
                  selectType('gallery', tag);
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  // 选择图片上传形式 - 相机或相册
  void selectType(String imageType, String tag) async {
    // 1. 创建图片选择器
    ImagePicker picker = ImagePicker();
    // 2. 判断是拍照还是相册
    if (imageType == 'camera') {
      // 选择拍照 - 调用相机
      final XFile? image = await picker.pickImage(source: ImageSource.camera);
      if (image != null) {
        uploadAvatar(image.path, tag);
        // ToastUtil.showSuccess(image.path);
      }
    } else if (imageType == 'gallery') {
      // 选择相册
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        uploadAvatar(image.path, tag);
        // ToastUtil.showSuccess(image.path);
      }
    }
  }

  // 上传图片请求
  uploadAvatar(String path, String tag) async {
    // ToastUtil.showSuccess(path);
    // 1. 包装formData对象， 接口需要
    FormData fd = FormData.fromMap({
      "file": await MultipartFile.fromFile(path),
    });
    // 2. 发送请求 - 修改一下post请求
    try {
      var res = await http.post('/upload', data: fd);
      // print(res);
      if (res['code'] != 10000) return ToastUtil.showError('上传失败');
      setState(() {
        _formData[tag] = res['data']['url'];
      });
      ToastUtil.showSuccess('上传成功');
    } catch (e) {
      ToastUtil.showError('上传失败');
    }
  }

  // 点击房屋修改过来，根据id获取信息
  editHouse() async {
    // 1. 获取id
    if (widget.id != null) {
      String id = widget.id as String;
      // 2. 发请求
      try {
        var res = await http.get('/room/$id');
        if (res['code'] != 10000) {
          return ToastUtil.showError('${res['message']}');
        }
        print(res);
        setState(() {
          _formData.addAll(res['data']);
          nameController.text = res['data']['name'];
          mobileController.text = res['data']['mobile'];
        });
      } catch (e) {
        ToastUtil.showError('获取数据失败');
      }
    }
  }

  @override
  void initState() {
    super.initState();
    _formData.addAll(widget.houseData);
    editHouse();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_formData.containsKey('id') ? '修改房屋信息' : '添加房屋信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Stack(
        children: [
          ListView(
            padding: const EdgeInsets.only(top: 10, bottom: 60),
            children: [
              // 房屋信息
              Container(
                padding: const EdgeInsets.all(10),
                child: const Text(
                  '房屋信息',
                  style: TextStyle(
                    color: Color.fromARGB(255, 97, 94, 94),
                    fontSize: 16,
                  ),
                ),
              ),
              Container(
                color: Colors.white,
                padding: const EdgeInsets.only(
                  left: 10,
                  right: 10,
                  top: 15,
                  bottom: 15,
                ),
                child: Text(
                  '${_formData['point']}${_formData['building']}${_formData['room']}',
                ),
              ),
              // 业主信息
              Container(
                padding: const EdgeInsets.all(10),
                child: const Text(
                  '业主信息',
                  style: TextStyle(
                    color: Color.fromARGB(255, 97, 94, 94),
                    fontSize: 16,
                  ),
                ),
              ),
              // 业主姓名
              Container(
                color: Colors.white,
                padding: const EdgeInsets.only(left: 10, right: 10),
                child: TextField(
                  controller: nameController,
                  maxLength: 5,
                  decoration: const InputDecoration(
                    labelText: '姓名', // 输入框标题
                    hintText: '请输入业主姓名', // 提示语
                    hintStyle: TextStyle(color: Colors.grey), // 提示语颜色
                    border: InputBorder.none, // 边框样式
                  ),
                ),
              ),
              // 性别
              Container(
                color: Colors.white,
                padding: const EdgeInsets.only(left: 10, right: 10),
                child: Row(
                  children: [
                    const Text('性别', style: TextStyle(fontSize: 16)),
                    const SizedBox(width: 20),
                    Radio(
                      value: 1, // 1男 0女
                      groupValue: _formData['gender'], // 当前选中的value
                      // 点击事件
                      onChanged: (value) {
                        setState(() {
                          _formData['gender'] = value ?? '';
                        });
                      },
                    ),
                    const Text('男'),
                    const SizedBox(width: 10),
                    Radio(
                      value: 0,
                      groupValue: _formData['gender'],
                      onChanged: (value) {
                        setState(() {
                          _formData['gender'] = value ?? '';
                        });
                      },
                    ),
                    const Text('女'),
                  ],
                ),
              ),
              // 业主手机号
              Container(
                color: Colors.white,
                padding: const EdgeInsets.only(left: 10, right: 10),
                child: TextField(
                  controller: mobileController,
                  keyboardType: TextInputType.phone,
                  maxLength: 11,
                  decoration: const InputDecoration(
                    labelText: '手机号',
                    hintText: '请输入您的手机号',
                    hintStyle: TextStyle(color: Colors.grey),
                    border: InputBorder.none,
                  ),
                ),
              ),
              // 业主信息
              Container(
                padding: const EdgeInsets.all(10),
                child: const Text(
                  '本人身份证照片',
                  style: TextStyle(
                    color: Color.fromARGB(255, 97, 94, 94),
                    fontSize: 16,
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
                child: const Text(
                  '请拍摄证件原件，并使照片中证件边缘完整，文字清晰，光线均匀。',
                  style: TextStyle(
                    color: Color.fromARGB(255, 97, 94, 94),
                    fontSize: 12,
                  ),
                ),
              ),
              // 身份证正面
              Container(
                color: Colors.white,
                height: 320,
                padding: const EdgeInsets.all(10),
                child: _formData['idcardFrontUrl'] == ''
                    ? _buildAddIdcardPhoto('idcardFrontUrl', '上传人像面照片')
                    : _buildIdcardPhoto(
                        'idcardFrontUrl',
                        _formData['idcardFrontUrl'],
                      ),
              ),
              const SizedBox(height: 20),
              // 身份证反面
              Container(
                color: Colors.white,
                height: 320,
                padding: const EdgeInsets.all(10),
                child: _formData['idcardBackUrl'] == ''
                    ? _buildAddIdcardPhoto('idcardBackUrl', '上传国徽面照片')
                    : _buildIdcardPhoto(
                        'idcardBackUrl',
                        _formData['idcardBackUrl'],
                      ),
              ),

              const SizedBox(height: 20),
            ],
          ),
          Positioned(
            bottom: 10,
            left: 0,
            right: 0,
            child: Container(
              color: Colors.white,
              padding: EdgeInsets.all(10),
              child: ElevatedButton(
                onPressed: () {
                  submitData();
                },
                child: Column(
                  children: [
                    SizedBox(height: 8),
                    Icon(Icons.exit_to_app),
                    Text('提交审核'),
                    SizedBox(height: 8),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
